import type { CSSProperties } from 'react';
import React, { useState } from 'react';
import {
  AlipayCircleOutlined,
  LockOutlined,
  MobileOutlined,
  TaobaoCircleOutlined,
  UserOutlined,
  WeiboCircleOutlined,
} from '@ant-design/icons';
import { LoginForm, ProFormCaptcha, ProFormText } from '@ant-design/pro-components';
import { App, Col, Row, Space, Tabs } from 'antd';
import { useNavigate } from 'react-router-dom';
import styled from 'styled-components';
import logging from '@/assets/logging.jpg';
import { getUserInfo, login } from '@/api/modules/user';
import ThemeConfig from '@/config/theme';
import { setStorage, setToken } from '@/utils/storage';
import { store } from '@/store';
import { setLogin } from '@/store/reducer/theme/action';
import { isSuccessCode } from '@/utils/isSuccessCode';
import { setUserInfo } from '@/store/reducer/user/action';

type LoginType = 'phone' | 'account';

const iconStyles: CSSProperties = {
  color: 'rgba(0, 0, 0, 0.2)',
  fontSize: '18px',
  verticalAlign: 'middle',
  cursor: 'pointer',
};

const WitLogin = styled(LoginForm)`
  .ant-pro-form-login-header {
    height: unset;
  }
`;

const Login = () => {
  const [loginType, setLoginType] = useState<LoginType>('account');
  const navigate = useNavigate();
  const { message } = App.useApp();
  const items = [
    { label: '账户密码登录', key: 'account' },
    { label: '手机号登录', key: 'phone' },
  ];
  // 登录
  const onSubmit = async (values: any) => {
    try {
      const { data } = await login({ data: { ...values } });
      if (isSuccessCode(data)) {
        setToken(data.data.token);
        store.dispatch(setLogin(true));
        await getUserInfo({}).then(res => {
          if (isSuccessCode(res.data)) {
            store.dispatch(setUserInfo(res.data.data));
            setStorage('witKeyPath', ['/home']);
            document.title = '首页';
            setTimeout(() => navigate('/home', { replace: true }), 500);
          }
        });
      }
    } catch (errorInfo) {
      alert(errorInfo);
    }
  };
  return (
    <div
      style={{
        height: '100vh',
        backgroundImage: `url(${logging})`,
        backgroundSize: 'cover',
        backgroundRepeat: 'no-repeat',
      }}
    >
      <Row justify="end" align="middle">
        <Col style={{ backgroundColor: 'white', opacity: 0.9 }}>
          <WitLogin
            logo="https://github.githubassets.com/images/modules/logos_page/Octocat.png"
            title={ThemeConfig.title}
            subTitle="全球最大的代码托管平台"
            onFinish={onSubmit}
            actions={
              <Space>
                其他登录方式
                <AlipayCircleOutlined style={iconStyles} />
                <TaobaoCircleOutlined style={iconStyles} />
                <WeiboCircleOutlined style={iconStyles} />
              </Space>
            }
          >
            <Tabs
              centered
              activeKey={loginType}
              onChange={activeKey => setLoginType(activeKey as LoginType)}
              items={items}
            />
            {loginType === 'account' && (
              <>
                <ProFormText
                  name="userName"
                  fieldProps={{
                    size: 'large',
                    prefix: <UserOutlined className="prefixIcon" />,
                  }}
                  placeholder="请输入用户名"
                  rules={[
                    {
                      required: true,
                      message: '请输入用户名!',
                    },
                  ]}
                />
                <ProFormText.Password
                  name="password"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className="prefixIcon" />,
                  }}
                  placeholder="请输入密码"
                  rules={[
                    {
                      required: true,
                      message: '请输入密码！',
                    },
                  ]}
                />
              </>
            )}
            {loginType === 'phone' && (
              <>
                <ProFormText
                  fieldProps={{
                    size: 'large',
                    prefix: <MobileOutlined className="prefixIcon" />,
                  }}
                  name="mobile"
                  placeholder="手机号"
                  rules={[
                    {
                      required: true,
                      message: '请输入手机号！',
                    },
                    {
                      pattern: /^1\d{10}$/,
                      message: '手机号格式错误！',
                    },
                  ]}
                />
                <ProFormCaptcha
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className="prefixIcon" />,
                  }}
                  captchaProps={{
                    size: 'large',
                  }}
                  placeholder="请输入验证码"
                  captchaTextRender={(timing, count) => {
                    if (timing) {
                      return `${count} ${'获取验证码'}`;
                    }
                    return '获取验证码';
                  }}
                  name="captcha"
                  rules={[
                    {
                      required: true,
                      message: '请输入验证码！',
                    },
                  ]}
                  onGetCaptcha={async () => {
                    message.success('获取验证码成功！验证码为：1234');
                  }}
                />
              </>
            )}
          </WitLogin>
        </Col>
      </Row>
    </div>
  );
};

export default Login;
